package com.ctgu.demo.controller;

import com.ctgu.demo.utils.ApiResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/opsForSet")
public class OpsForSetController {

    private final RedisTemplate<String, Object> redisTemplate;

    public OpsForSetController(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private static final String USER_TAGS_KEY = "user:1001:tags";
    private static final String GROUP_TEAM_A_KEY = "group:teamA";
    private static final String GROUP_TEAM_B_KEY = "group:teamB";

    // http://localhost:8080/opsForSet/label
    // 用户兴趣标签管理：每个用户可以选择多个兴趣标签，这些标签可以存储在 Redis 中，不会重复。
    @GetMapping("label")
    public ApiResult label() {
        // 添加用户兴趣标签
        redisTemplate.opsForSet().add(USER_TAGS_KEY, "Sports", "Music", "Travel");
        // 获取所有标签
        Set<Object> tags = redisTemplate.opsForSet().members(USER_TAGS_KEY);
        return ApiResult.success("成功获取所有标签", tags);
    }

    // http://localhost:8080/opsForSet/userGroup
    // 用户群组管理：用户可能属于多个群组，快速查询两个群组的共同成员。
    @GetMapping("userGroup")
    public ApiResult userGroup() {
        // 添加群组成员
        redisTemplate.opsForSet().add(GROUP_TEAM_A_KEY, "Alice", "Bob", "Charlie");
        redisTemplate.opsForSet().add(GROUP_TEAM_B_KEY, "Bob", "David", "Charlie");

        // 获取两个群组的共同成员
        Set<Object> commonMembers = redisTemplate.opsForSet().intersect(GROUP_TEAM_A_KEY, Collections.singleton(GROUP_TEAM_B_KEY));

        Map<String, Object> result = new HashMap<>();
        result.put("commonMembers", commonMembers);
        return ApiResult.success("共同成员", result);
    }
}
